package com.rms.hkpc.signalr;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.microsoft.signalr.HubConnectionState;
import com.microsoft.signalr.OnClosedCallback;
import com.rms.hkpc.constant.AllConstants;
import com.rms.hkpc.util.SPUtil;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

public class SignalRChannel {
    private String url;
    private HubConnection hubConnection;
    private Handler receiveHandler;
    private long lastRecvTime = 0;
    private Timer timer;
    // 创建消息队列
    private Queue<SendMessage> sendMessageQueue = new LinkedList<>();

    public boolean isConnected() {
        if (hubConnection != null) {
            return hubConnection.getConnectionState() == HubConnectionState.CONNECTED;
        }
        return false;
    }

    public SignalRChannel(String url, Handler handler) {
        this.url = url;
        this.receiveHandler = handler;
        timer = new Timer();
    }

    /**
     * 开启连接
     */
    public void startConnect() {
        if (hubConnection == null) {
            hubConnection = HubConnectionBuilder.create(url)
                    .withHeader("token", SPUtil.getInstance().getString(AllConstants.TOKEN))
                    .build();
            hubConnection.setKeepAliveInterval(2 * 60 * 1000);
            hubConnection.setServerTimeout(4 * 60 * 1000);
        }
        startSync();
        setOn();
    }

    public synchronized void startSync() {
        try {
            Log.i(AllConstants.TAG,"startSync：11");
            hubConnection.start().blockingAwait();
            send(SignalRCode.LOGIN, SPUtil.getInstance().getString(AllConstants.ID));
        } catch (Exception e) {
//            timer.schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    startSync();
//                }
//            }, 5000);
            e.printStackTrace();
        }
    }

    /**
     * 接收消息
     */
    private void setOn() {
        // hubConnection关闭回调
        hubConnection.onClosed(new OnClosedCallback() {
            @Override
            public void invoke(Exception exception) {
                startSync();
            }
        });
        // 消息封装，多余一个参数的封装进json，方便后面提取
        // 一个参数的，直接放到obj中，在接收的地方根据类型来处理
        hubConnection.on(SignalRCode.RECEIVE_MSG, (msgType, message) -> {
            Log.i(AllConstants.TAG, "msgType:" + msgType);
            Log.i(AllConstants.TAG, "message:" + message);
            if (msgType.equals(SignalRCode.PUSH)) {
                Message msg = Message.obtain();
                msg.what = SignalRCode.RECEIVE_NUM;
                msg.obj = message;
                MessageReceived(msg);
            }
        }, String.class, String.class);
    }

    /**
     * 将接收到的消息发送出去
     *
     * @param msg
     */
    private void MessageReceived(Message msg) {
        lastRecvTime = System.currentTimeMillis() / 1000;
        Runnable receivedRun = new Runnable() {
            @Override
            public void run() {
                receiveHandler.sendMessage(msg);
            }
        };
        new Thread(receivedRun).start();
    }

    /**
     * 发送消息
     *
     * @param method
     * @param message
     */
    public void send(String method, Object... message) {
        try {
            hubConnection.send(method, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 关闭连接
     */
    public void stopConnect() {
        if (hubConnection != null) {
            hubConnection.stop();
            hubConnection.close();
        }
    }

}
